<?php
class SchedulesController extends AppController
{
	var $name = 'Schedules';
	var $helpers = array('Html', 'Form');
	var $components = array('Email');
	var $Schedule ;
	function send($id = false)
	{
		$this->autoRender = false;
		$schedules = null;
		if($id)
		{
			$schedules = $this->Schedule->findById($id);
			$schedules = array($schedules);
		}
		else
		{
			//$schedule = $this->Schedule->find('first',array('conditions'=>array('NOT'=>array('status'=>Schedule::COMPLETED))));
			$schedules = $this->Schedule->find('all',array('conditions'=>array('NOT'=>array('status'=>Schedule::COMPLETED))));
		}
		if(!$schedules || empty($schedules))
		{
			echo __("No pending newsletters found.")." \n";
			return;
		}
		foreach ($schedules as $schedule)
		{
			$scheduleId = $schedule['Schedule']['id'];
			$allowSending = $this->Schedule->allowNewsletterSend($schedule['Schedule']['id']);
			
			if($allowSending == false)
			{
				echo sprintf(__("Schedule %d is not allowed to send newsletter at this time."),$schedule['Schedule']['id']);
				continue; //return;
			}
			echo __("Found pending newsletter to send.. Preparing send procedure now..")." \n ";
			$recipients = $this->Schedule->getRecipient($schedule);
			$i = 0;
			//$this->set('unsubscribeLink',$schedule['Schedule']['condition'] != Schedule::ALL_USER);
			$this->Schedule->id = $schedule['Schedule']['id'];
			$this->Schedule->saveField('status', Schedule::SENDING);
			$this->Schedule->logLastActivity($scheduleId);
			echo count($recipients)." recipients found!\n";
			if(isset($schedule['Newsletter']['newsletter_type']) && !is_null($schedule['Newsletter']['newsletter_type']) && $schedule['Newsletter']['newsletter_type'])
			{
				$schedule['Newsletter']['body_html'] = $this->Schedule->Newsletter->getContentForNewsletterType($schedule['Newsletter']['newsletter_type']);
				$schedule['Newsletter']['body_text'] = $schedule['Newsletter']['body_html'];
			}
			foreach($recipients as $recipient)
			{
				//pings mysql server to check if server has gone away.
				if(!$this->Schedule->field('id',array('id'=>$scheduleId)))
				{
					$this->_stop();
				}
				$this->Schedule->logLastActivity($scheduleId);
				$sendMail = true;
				if($this->Schedule->hasSent($scheduleId,$recipient))
				{
					$sendMail = false;
				}	
				if($sendMail == true)
				{
					// add a delay if enabled
					if(cr('Newsletter.waitTime'))
					{
						if($i % cr('Newsletter.maxEmailsInInterval') == 0)
						{
							sleep(cr('Newsletter.waitTime'));
						}
					}
					$this->sendMail($recipient,$schedule);
					$this->Schedule->logSend($scheduleId,$recipient);
					$this->Schedule->logLastActivity($scheduleId);
				}
				$i++;
			}
			echo __("Newsletter sent!")." \n ";
			$this->Schedule->id =$scheduleId;
			$this->Schedule->saveField('status', Schedule::COMPLETED);
			$this->Schedule->cleanSendLogs($scheduleId);	
		}
	}

	private function sendMail($recipient,$schedule)
	{
		$this->Email->reset();
		$this->Email->to = $recipient['email'];
		//$unsubscribeLink = "<a href='".cr('cmsConfig.Backend.siteUrl').'/newsletters/subscribers/change/'.$recipient['code']."'>Click here to unsubscribe</a>";
		$unsubscribeLink = cr('cmsConfig.Backend.siteUrl').'/newsletters/subscribers/change/'.@$recipient['code'];
		
		$this->set('unsubscribe_link',$unsubscribeLink);
		$this->set(array_keys($recipient),array_values($recipient));
		$this->Email->sendAs = 'both';
		$this->Email->subject = $schedule['Newsletter']['subject'];
		$this->Email->setFrom(cr('cmsConfig.Backend.websiteEmail'));
		$this->Email->return = cr('Newsletter.returnEmail');
		$this->Email->template = 'newsletter_body';
		$this->set('body_html',$schedule['Newsletter']['body_html']);
		$this->set('body_text',$schedule['Newsletter']['body_text']);
		$this->set('body',$schedule['Newsletter']['body_html']);
		
		$this->Email->send();
	}

	function admin_add($id = null)
	{
		if (!$id) {
			$this->Session->setFlash(__('Invalid Newsletter', true));
			$this->redirect(array('action'=>'index'));
		}
		if($this->data)
		{
			$this->data['Schedule']['newsletter_id'] = $id;
			$this->Schedule->create();
			if($this->Schedule->save($this->data))
			{
				$this->successMsg(__('Newsletter has been scheduled'));
				$this->redirect(array('action'=>'admin_index','controller'=>'newsletters'));
			}
		}
		$this->pageTitle = __("Schedules");
		
		$newsletter = $this->Schedule->Newsletter->findById($id);
		$this->set('newsletter',$newsletter);
	}
	
	private function _ide()
	{
		$this->Schedule = new Schedule();	
	}

}
?>
